package com.kob.backend.utils;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Component
public class DateTimeUtils {

    // 获取当前系统时间，返回String
    @Bean
    public String getCurrentDateTime() {
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return currentDateTime.format(formatter);
    }

//    @Bean
    // 将日期和时间段转为开始日期+时间和结束日期+时间
    public String[] GetSatrtEndTime(String dateslot, String timeslot)
    {
        try {
            // 解析日期
            LocalDate date = LocalDate.parse(dateslot, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            // 解析时间范围
            String[] timeRange = timeslot.split("~");
            LocalTime startTime = LocalTime.parse(timeRange[0], DateTimeFormatter.ofPattern("HH:mm"));
            LocalTime endTime = LocalTime.parse(timeRange[1], DateTimeFormatter.ofPattern("HH:mm"));

            // 合并为LocalDateTime
            LocalDateTime startDateTime = LocalDateTime.of(date, startTime);
            LocalDateTime endDateTime = LocalDateTime.of(date, endTime);

            // 输出格式化后的字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            String[] formattedTime = new String[2];
            formattedTime[0] = startDateTime.format(formatter);
            formattedTime[1] = endDateTime.format(formatter);

            return formattedTime;
        } catch (Exception e) {
            e.printStackTrace();
            return new String[]{"Invalid Input", "Invalid Input"};
        }
    }

    // 判段当前时间是不是在那几个空闲时间内
    public boolean IsInTimeSlot(LocalTime currentTime) {
        // "09:00~09:10", "11:10~11:20", "13:20~13:30", "15:30~15:40",
        // "17:40~17:50", "19:50~20:00", "23:00"
        String[] timeRanges = {"09:00~09:00", "11:10~11:20", "13:20~13:30", "15:30~15:40", "17:40~17:50", "19:50~20:00", "23:00~23:10"};

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");

        for (String timeRange : timeRanges) {
            String[] parts = timeRange.split("~");
            if (parts.length == 2) {
                String startTimeString = parts[0].trim();
                String endTimeString = parts[1].trim();

                LocalTime startTime = LocalTime.parse(startTimeString, formatter);
                LocalTime endTime = LocalTime.parse(endTimeString, formatter);

                if (currentTime.isAfter(startTime) && currentTime.isBefore(endTime)) {
                    return true;
                }
            }
        }
        return false;
    }
}
